# -*- coding: utf-8 -*-
import os.path
import wx
import random
import util
from concept import Concept, load
from card import Card

class Painter(object):
    "Wraps a panel, provides simple high level operations for drawing on canvas"
    def __init__(self, canvas):
        self.canvas = canvas
        self.dc = wx.PaintDC(self.canvas)
        self.fw, self.fh = self.canvas.GetSize()
        font = wx.Font(100.0, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
        self.dc.SetFont(font)
        
    def draw_image(self, image, rescale=True):
        "Draws a wx.Image in the center of the canvas."
        iw, ih = [image.GetWidth(), image.GetHeight()]
        
        if rescale:
            ih *= (float(self.fw) / iw)
            iw = self.fw
            if ih > self.fh:
                iw *= (float(self.fh) / ih)
                ih = self.fh 
            bmp = image.Scale(int(iw), int(ih)).ConvertToBitmap()
        else:
            bmp = image.ConvertToBitmap()
                
        ix, iy = self.center(iw, ih)
        self.dc.DrawBitmap(bmp, ix, iy)
        
    def draw_text(self, text):
        "Draws a single line string of text, centered vertically"
        self.set_font_size_to_fit(text)
        tw, th = self.dc.GetTextExtent(text)
        tx, ty = self.center(tw, th)
        self.dc.DrawText(text, tx, ty)
        
    def set_font_size_to_fit(self, text):
        "Gives the max point size to fit the text within the canvas."
        font = self.dc.GetFont()
        font.SetPointSize(100.0)
        self.dc.SetFont(font)
        tw, th = self.dc.GetTextExtent(text)
        scale = self.fw / float(tw)
        th *= scale
        if th > self.fh:
            scale *= (self.fh / float(th))
        font.SetPointSize(100.0 * scale)
        self.dc.SetFont(font)

    def center(self, width, height):
        "Given a width, and height, returns the x, y coordinates to make the object centered."
        x = (self.fw - width) / 2
        y = (self.fh - height) / 2
        return int(x), int(y)

class FlashCardFrame(wx.Frame):
    CYCLE_INTERVAL = 2000
    
    def __init__(self, parent, title, cards):
        wx.Frame.__init__(self, parent, title=title, size=(420,460))
        
        self.res = {
            'speaker': wx.Image(os.path.join(util.resource_folder, u"speaker.jpg"))
                    }
        
        self.cards = cards
        self.content = None
        self.init_ui()
        self.next()
        #self.event_loop = pyglet.app.EventLoop()
        self.Centre()
        self.Show(True)


    def init_ui(self):
        panel = wx.Panel(self)
        panel.SetBackgroundColour("#ffffff")
        
        self.content_frame = wx.Panel(panel, style=wx.BORDER_SIMPLE)
        self.content_frame.SetBackgroundColour("#ffffff")
        self.content_frame.Bind(wx.EVT_PAINT, self.on_paint_content)
        self.content_frame.Bind(wx.EVT_SIZE, self.on_resize_content)
        
        buttons = wx.Panel(panel)
        #buttons.SetBackgroundColour("#ffffff")
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        flip = wx.Button(buttons, -1, "Flip")
        self.Bind(wx.EVT_BUTTON, self.flip, flip)
        hbox.Add(flip, 0)
        next = wx.Button(buttons, -1, "Next")
        self.Bind(wx.EVT_BUTTON, self.next, next)
        hbox.Add(next, 0, wx.LEFT, 5)
        buttons.SetSizer(hbox)
        
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.content_frame, 1, wx.EXPAND | wx.ALL, 10)
        vbox.Add(buttons, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10)
        panel.SetSizer(vbox)
        
        self.timer = wx.Timer(self, 1000)
        self.timer.Start(self.CYCLE_INTERVAL)
        wx.EVT_TIMER(self, 1000, self.on_timer)
        wx.EVT_CLOSE(self, self.on_close)
        
    def refresh(self):
        self.content_frame.Refresh()
        
    def cycle(self, event=None):
        if self.card.cycle():
            self.refresh()
        
    def flip(self, event=None):
        self.card.flip()
        self.refresh()
    
    def next(self, event=None):
        self.card = random.choice(self.cards)
        self.card.random_side()
        self.card.activate()
        self.refresh()
        
    def on_paint_content(self, event):
        painter = Painter(self.content_frame)
        self.card.render(painter)
           
    def on_resize_content(self, event):
        self.refresh()
        
    def on_close(self, event):
        #self.event_loop.exit()
        self.timer.Stop()
        self.Destroy()
    
    def on_timer(self, event):
        self.cycle()

if __name__ == '__main__':
    cards = []
    concept_parent_folder = os.path.join(util.resource_folder, u"concept")
    
    for dirname, dirnames, filenames in os.walk(concept_parent_folder):
        if " - " not in os.path.split(dirname)[-1]: continue
        concept = load(dirname)
        card = Card(concept)
        cards.append(card)

    app = wx.App(False) 
    frame = FlashCardFrame(None, "Flashcards", cards)
    app.MainLoop()





